<template>
  <div class="addOrderStyle">
    <!--立即下单-->
    <el-dialog
      title="立即下单"
      :beforeClose="handleClose"
      modal-append-to-body
      append-to-body
      :visible.sync="dialogVisible"
      v-loading="dialogLoading"
      width="1300px"
    >
      <el-form
        :model="sendForm"
        ref="sendForm"
        label-width="160px"
        style="width: 95%"
        size="mini"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称：" prop="customerId">
              <el-select
                :disabled="this.type == 'inquiryIds'"
                clearable
                v-model="sendForm.customerId"
                filterable
                remote
                placeholder="请输入关键词"
                @change="handleChange"
                :remote-method="companyQuerySearch"
              >
                <el-option
                  v-for="item in companyQuerySearchList"
                  :key="item.customerId"
                  :label="item.customerName"
                  :value="item.customerId"
                >
                </el-option>
              </el-select>
              <div style="padding-left:15px;color:red;font-size: 12px" v-if="isEnableOrder === 0">注意:该客户最近1年存在降价违约{{ defaultNum }}次,超期未清款{{outTimeUnPaidAmount}}元，限制询盘和下单!</div>
            </el-form-item>
            <el-form-item label="客户标签:" v-if="customerTag">
              <crm-tag :item="item" v-for="item in customerTag" :key="item.tagName" style="margin-bottom:4px;margin-right:4px"></crm-tag>
            </el-form-item>
            <el-form-item label="负责人:">
              {{ chargeName }}
            </el-form-item>
            <el-form-item label="协助人:">
              {{ subChargeNames }}
            </el-form-item>
       <!-- <el-form-item label="业务员:" v-if="inquiryUserList.length==1">-->
       <!--   {{ inquiryUserList[0].userName }}-->
       <!-- </el-form-item>-->
            <el-form-item label="业务员:"  prop="inquiryUserId">  <!--v-if="inquiryUserList.length>1"  2024-10-29  需求提出按公司检索业务员，无业务员负责的公司不能下单-->
            <el-select
              v-model="sendForm.inquiryUserId"
              clearable
              filterable
            >
              <el-option
                v-for="item in inquiryUserList"
                :key="item.userId"
                :value="item.userId"
                :label="item.userName"
              ></el-option>
            </el-select>
          </el-form-item>
            <el-form-item label="供货方：">
              <span>{{ sendForm.fromCompany }}</span>
            </el-form-item>
<!--            <el-form-item label="付款截止时间：" prop="payDate">-->
<!--              <el-date-picker-->
<!--                value-formate="yyyy-MM-dd hh:mm:ss"-->
<!--                v-model="sendForm.payDate"-->
<!--                style="width: 180px; display: inline-block"-->
<!--                type="datetime"-->
<!--                default-time="17:00:00"-->
<!--                :picker-options="pickerOptions1"-->
<!--                placeholder="选择日期时间"-->
<!--                >-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
            <el-form-item
              label="收货地址："
              prop="addressId"
              v-if="sendForm.sendTypes != '自提'"
            >
              <div>
                <span>可用地址：</span>
                <el-radio-group
                  v-if="canUseAddressList.length > 0 && sendForm.customerId"
                  v-model="sendForm.addressId">
                  <div v-for="item in canUseAddressList" :key="item.id" class="areaInfoRadio">
                    <el-radio
                      :label="item.id"
                      :value="item.areaInfo"
                      style="margin-top: 10px"
                      border
                    >
                      <div style="display: inline-block">
                        <span>{{ item.contacts }}</span>
                        <span style="padding-left: 5px">{{ item.mobile }}</span>
                        <span style="padding-left: 10px">{{ item.areaInfo }}</span>
                        <div style="line-height: 18px;color:Red">真实地址：{{item.address}}</div>
                        <div style="line-height: 18px">展示地址：{{item.openAddress}}</div>
                      </div>
                      <span
                        style="
                          text-decoration: underline;
                          color: red;
                          display: inline-block;
                          margin-left: 10px;
                          cursor: pointer;
                        "
                        @click="showAddAddress('edit', item)">修改</span>
                      <span
                        style="
                          text-decoration: underline;
                          color: red;
                          display: inline-block;
                          margin-left: 10px;
                          cursor: pointer;
                        "
                        @click="showDelAddress(item)">删除</span>
                    </el-radio>
                  </div>
                </el-radio-group>
              </div>
              <div>
                <span
                  style="font-size: 12px; padding-right: 10px"
                  v-if="canUseAddressList.length == 0"
                  >暂无地址</span>
                <el-button
                  type="text"
                  @click="showAddAddress('add', sendForm)"
                  :disabled="!sendForm.customerId"
                  >新增地址</el-button>
              </div>
              <div>
                <span>不可用地址：</span>
                <el-radio-group v-if="noUseAddressList.length > 0 && sendForm.customerId">
                  <div v-for="item in noUseAddressList" :key="item.id" class="areaInfoRadio">
                    <el-radio
                      disabled
                      :label="item.id"
                      :value="item.areaInfo"
                      style="margin-top: 10px"
                      border>
                      <div style="display: inline-block">
                        <span>{{ item.contacts }}</span>
                        <span style="padding-left: 5px">{{ item.mobile }}</span>
                        <span style="padding-left: 10px">{{ item.areaInfo }}</span>
                        <div style="line-height: 18px;color:Red">真实地址：{{item.address}}</div>
                        <div style="line-height: 18px">展示地址：{{item.openAddress}}</div>
                      </div>
                      <span
                        style="
                          text-decoration: underline;
                          color: red;
                          display: inline-block;
                          margin-left: 10px;
                          cursor: pointer;
                        "
                        @click.stop="showAddAddress('edit', item)">修改</span>
                      <span
                        style="
                          text-decoration: underline;
                          color: red;
                          display: inline-block;
                          margin-left: 10px;
                          cursor: pointer;
                        "
                        @click.stop="showDelAddress(item)">删除</span>
                    </el-radio>
                  </div>
                </el-radio-group>
              </div>
              <div>
                <span
                  style="font-size: 12px; padding-right: 10px"
                  v-if="noUseAddressList.length == 0"
                  >暂无地址</span>
              </div>
            </el-form-item>

            <!-- 发货联系人 -->
            <el-form-item label="发货联系人：">
               <div v-if="sendForm.customerId">
                 <el-select v-model="deliverMobile" :loading="contactLoading" placeholder="请选择发货联系人" clearable @focus="handleDeliverMobile">
                    <el-option
                      v-for="(item,index) in deliverMobileList"
                      :key="index"
                      :label="item.contactMobile"
                      :value="item.contactMobile">
                    </el-option>
                 </el-select>
                 <el-button
                  type="text"
                  @click="showContact('add', sendForm,'发货联系人')"
                  >新增发货联系人</el-button>
               </div>
            </el-form-item>

            <!-- 发票联系人 -->
            <el-form-item label="发票联系人：">
              <div v-if="sendForm.customerId">
                <el-select v-model="invoiceMobile" :loading="contactLoading" placeholder="请选择发票联系人" clearable @focus="handleInvoiceMobile">
                  <el-option
                    v-for="(item,index) in invoiceMobileList"
                    :key="index"
                    :label="item.contactMobile"
                    :value="item.contactMobile">
                  </el-option>
                </el-select>
                <el-button
                  type="text"
                  @click="showContact('add', sendForm,'发票联系人')"
                  >新增发票联系人</el-button>
              </div>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="收货方式：" prop="sendTypes">
              {{ sendForm.sendTypes }}
            </el-form-item>
            <el-form-item
              label="运费方式："
              prop="shippingType"
              v-if="sendForm.sendTypes != '自提'"
            >
              <el-radio-group v-model="sendForm.shippingType">
                <el-radio label="free_shipping"
                  >供方承担运输费用（免运费）</el-radio
                >
                <el-radio label="logistics_shipping">需方承担运输费用</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="支付方式：" prop="payTypes">
              <el-radio-group v-model="sendForm.payTypes" @input="changePayTypes(sendForm.payTypes)">
                <el-radio
                  v-for="(item,index) in paymentTypeLists"
                  :key="index"
                  :label="item.code"
                  style="margin-bottom: 10px;"
                  >{{ item.name }}</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="支付摘要：">
               <div style="padding:16px 10px 10px 20px;border: 1px solid #ccc;border-radius:10px;" v-if="sendForm.payTypes">
                  <!-- 款到发货 -->
                  <div v-if="sendForm.payTypes=='BANK_PAY'">
                    <el-form-item prop="paymentItemCode">
                      <el-radio-group v-model="sendForm.paymentItemCode" @input="changePaymentCode">
                        <el-radio
                          v-for="(item,index) in choosePaytypeObj.itemList"
                          :key="index"
                          :label="item.paymentItemCode"
                          style="margin-bottom:10px;display: block"
                          >{{ item.paymentItemName }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <!--定金支付-->
                    <div v-if="sendForm.paymentItemCode=='BANK_PAY_Item3'">
                      <div>
                        <span> <span style="color: red;">*</span> 支付定金</span>
                        <span style="color: red;">(不低于全款的20%)</span>
                      </div>
                      <el-form-item style="margin-bottom: 10px;" prop="paymentDeposit">
                        <el-input type="number" v-model="sendForm.paymentDeposit" clearable style="width: 150px;"></el-input> 元
                      </el-form-item>
                      <div>
                        <span> <span style="color: red;">*</span> 货款最晚付清日期</span>
                        <span style="color: red;">(不得超过30天)</span>
                      </div>
                      <el-form-item style="margin-bottom: 10px;" prop="paymentDate">
                        <el-date-picker
                          style="width: 150px;"
                          :picker-options="pickerOptions2"
                          v-model="sendForm.paymentDate"
                          value-format="yyyy年MM月dd日"
                          type="date"
                          placeholder="选择日期">
                        </el-date-picker>
                      </el-form-item>
                    </div>
                    <!--分批支付-->
                    <div v-if="sendForm.paymentItemCode=='BANK_PAY_Item4'">
                      合同签订当日支付定金（<span style="color:Red">不低于全款的20%</span>）
                      <el-form-item style="margin-bottom: 10px;display: inline-block" prop="paymentDeposit">
                        <el-input type="number" v-model="sendForm.paymentDeposit" clearable style="width: 100px" @change="countperDeposit"></el-input>
                      </el-form-item> 元，付完一车，发一车，定金用于最后一车的货款抵扣。
                      合同最晚付款时间
                      <el-form-item style="margin-bottom: 10px;display: inline-block" prop="paymentDate">
                        <el-date-picker
                          style="width: 150px;"
                          :picker-options="pickerOptions2"
                          v-model="sendForm.paymentDate"
                          value-format="yyyy年MM月dd日"
                          type="date"
                          placeholder="选择日期">
                        </el-date-picker>
                      </el-form-item>

                    </div>
                  </div>
                  <!-- 货到付款 货到票到付款 -->
                  <div v-if="sendForm.payTypes=='COD_PAY'||sendForm.payTypes=='COD_PAY2'">
                    <div>
                      <span>合同当日支付定金</span>
                      <span
                        v-if="(sendForm.payTypes=='COD_PAY'&&sendForm.paymentItemCode!='COD_PAY_Item2')||(sendForm.payTypes=='COD_PAY2'&&sendForm.paymentItemCode!='COD_PAY2_Item2')"
                        style="color: red;">
                        (不低于全款的5%)
                      </span>
                    </div>
                    <el-form-item style="margin-bottom: 12px;" prop="paymentDeposit">
                      <el-input type="number" v-model="sendForm.paymentDeposit" clearable style="width: 150px;"></el-input> 元
                    </el-form-item>
                    <el-form-item prop="paymentItemCode">
                      <el-radio-group v-model="sendForm.paymentItemCode"  @input="changePaymentCode">
                        <div v-for="(item,index) in choosePaytypeObj.itemList" :key="index" style="margin-bottom: 10px;">
                          <el-radio :label="item.paymentItemCode">{{ item.paymentItemName }}</el-radio>
                        </div>
                      </el-radio-group>
                    </el-form-item>
                    <!--货到付款 货到票到付款，有账期-->
                    <div style="color:red;" v-if="sendForm.paymentItemCode=='COD_PAY_Item2'||sendForm.paymentItemCode=='COD_PAY2_Item2'">
                      请事先与相关经理沟通该客户是否符合账期规定
                    </div>
                    <!--货到付款，无账期-->
                    <div style="color:red;line-height: 20px" v-if="sendForm.paymentItemCode=='COD_PAY_Item1'">
                      需要注意发货后与物流联系确认客户款清之后再卸货!<br/>厂发物流需要司机信息出现之后就付清货款!
                    </div>
                    <!-- 有账期 -->
                    <div v-if="sendForm.paymentItemCode=='COD_PAY_Item2'||sendForm.paymentItemCode=='COD_PAY2_Item2'">
                      <div> <span style="color: red;">*</span> 客户账期(天)</div>
                      <el-form-item style="margin-bottom: 10px;" prop="paymentDayNum">
                        <el-input type="number" v-model="sendForm.paymentDayNum" clearable style="width: 150px;"></el-input>
                      </el-form-item>
                      <div> <span style="color: red;">*</span> 账期利息(元/吨/天) <span style="padding-left:5px;color:red">合同单价*0.0003</span></div>
                      <el-form-item style="margin-bottom: 10px;" prop="paymentInterest">
                        <el-input type="number" v-model="sendForm.paymentInterest" clearable style="width: 150px;"></el-input>
                      </el-form-item>
                    </div>
                    <div> <span style="color: red;">*</span> 货款最晚付清日期</div>
                    <el-form-item style="margin-bottom: 10px;" prop="paymentDate">
                      <el-date-picker
                        style="width: 150px;"
                        v-model="sendForm.paymentDate"
                        :picker-options="pickerOptions1"
                        value-format="yyyy年MM月dd日"
                        type="date"
                        placeholder="选择日期">
                      </el-date-picker>
                    </el-form-item>
                  </div>
                  <!-- 摩塑白条 -->
                  <div v-if="sendForm.payTypes=='XISHANG_PAY'">
                    <div> <span style="color: red;">*</span> 需方向锡商银行贷款(元)</div>
                    <el-form-item style="margin-bottom: 10px;" prop="paymentAmount">
                      <el-input type="number" v-model="sendForm.paymentAmount" clearable style="width: 150px;"></el-input>
                    </el-form-item>
                    <div> <span style="color: red;">*</span> 贷款期限(天)</div>
                    <el-form-item style="margin-bottom: 10px;" prop="paymentDayNum">
                      <el-input type="number" v-model="sendForm.paymentDayNum" clearable style="width: 150px;"></el-input>
                    </el-form-item>
                    <div style="color: #ff6501;">贷款利率根据企业实际批准利率,款到发货,贷款自合同签订日起当日付清</div>
                  </div>
               </div>
            </el-form-item>

            <el-form-item
              label="客户是否有未清款项："
              prop="isArrears"
              v-if="sendForm.payTypes=='COD_PAY'||sendForm.payTypes=='COD_PAY2'||sendForm.payTypes=='XISHANG_PAY'">
              <el-radio-group v-model="sendForm.isArrears" @input="changeArrears">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="sendForm.isArrears==1" label="未清款项款项说明：" prop="arrearsRemark">
              <el-input v-model="sendForm.arrearsRemark" clearable placeholder="请填写未清款项款项说明"></el-input>
            </el-form-item>
            <el-form-item v-if="sendForm.isArrears==1" label="客户信誉：" prop="reputation">
              <el-input v-model="sendForm.reputation" clearable placeholder="请填写客户信誉"></el-input>
            </el-form-item>
            <el-form-item  label="" prop="exchangeRate">
              <template slot="label">
                <div style="display: inline-block">
                  <el-tooltip class="item" effect="light" placement="bottom-start">
                    <div><span style="vertical-align: middle">外贸订单美金汇率</span><i class="el-icon-question" style="color:#606266;font-size: 16px;vertical-align: middle;padding-left:5px;"></i></div>
                    <div slot="content" style="max-width:400px;">内销订单默认为1，外贸订单需要根据实时汇率进行填写</div>
                  </el-tooltip>
                </div>

              </template>
              <el-input-number
                placeholder="非外贸订单填写1"
                v-model="sendForm.exchangeRate"
                :precision="4"
                controls-position="right"
                :controls="false"
              ></el-input-number>
            </el-form-item>
            <el-form-item  label="订单分类：" prop="orderCustomerType" v-if="orderCustomerType == ''">
              <el-select v-model="sendForm.orderCustomerType" filterable clearable>
                <el-option
                  v-for="(item,index) in orderCustomerTypeList"
                  :key="index"
                  :label="item.cddValue"
                  :value="item.cddValue">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item  label="订单分类：" v-else>
              {{sendForm.orderCustomerType}}
            </el-form-item>
            <el-form-item  label="是否分批来款，分批发货：" prop="isBatchPaid" label-width="166px">
                <el-radio-group v-model="sendForm.isBatchPaid" :disabled="sendForm.paymentItemCode=='BANK_PAY_Item4' || inpuiryIsBatchPaid == 1">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item  label="是否意向订单：" prop="isIntentionOrder" label-width="166px">
              <el-radio-group v-model="sendForm.isIntentionOrder">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
              <span style="color:red;padding-left: 5px" v-if="sendForm.isIntentionOrder == 1">和客户约定预售订单需当日回传合同才能生效</span>
            </el-form-item>
            <el-form-item  label="" prop="isDelaySettleOrder" label-width="166px">
              <template slot="label">
                <div style="display: inline-block">
                  <el-tooltip class="item" effect="light" placement="bottom-start">
                    <div><span style="vertical-align: middle">是否后结算订单：</span><i class="el-icon-question" style="color:#606266;font-size: 16px;vertical-align: middle;padding-left:5px;"></i></div>
                    <div slot="content" style="max-width:400px;">后结算订单：销售预估毛利必须为0;支付方式为【款到发货】</div>
                  </el-tooltip>
                </div>
              </template>
              <el-radio-group v-model="sendForm.isDelaySettleOrder">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="margin: 10px 0">
          <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
          <span class="font-small">商品信息</span>
          <span v-if="isPayTypes" style="padding-left:5px;color:Red;">
            承兑注意:公司承兑账号
            <el-popover
              placement="bottom"
              max-width="500"
              v-model="visible">
                <div style="margin-bottom: 16px;padding: 12px;border-radius: 8px;background: #ecf5ff;" v-for="item in chengDuiBankList">
                    <div>账户名称：{{ item.fromCompany }}</div>
                    <div>承兑账号：{{ item.bankAccount }}</div>
                    <div>开户银行：{{ item.bankName }}</div>
                    <div>行<span style="padding-left:27px">号：</span>{{ item.bankCode }}</div>
                    <div style="text-align: right; margin-top: 10px">
                      <el-button type="primary" size="mini" @click="copyItem(item)">复制</el-button>
                    </div>
                </div>
                <el-button size="small" style="padding:5px 10px" type="danger" plain round slot="reference">查看</el-button>
            </el-popover>
            ，重复背书及6个月以内可转让的银行承兑不收，拒收与推荐承兑附件 <el-button size="small" style="padding:5px 10px" type="danger" plain round @click="downFile">下载</el-button>
          </span>
        </div>
        <el-table
          size="mini"
          :header-cell-style="{ background: '#f8f8f9', color: '#80878f' }"
          :data="sendForm.goodsList"
          id="my-table"
          border
          style="width: 100%; padding: 0"
        >
          <el-table-column
            width="150"
            fixed="left"
            label="品名牌号"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span
                  >{{ scope.row.categoryName }}/{{ scope.row.goodsSn }}</span
                >
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="150" label="仓库" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span>{{ scope.row.warehouseName }}</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            width="100"
            fixed="left"
            label="采购单价"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span>{{ scope.row.purchasePrice }}</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="100" label="结算方式" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span>{{ scope.row.payTypes }}</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="成交数量(吨)" width="100px" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="`goodsList.${scope.$index}.goodsNum`"
                :rules="rules.goodsNum"
                label-width="0px"
              >
                <el-input
                  v-model="scope.row.goodsNum"
                  :disabled="type != 'onePrice'"
                  type="number"
                  size="small"
                  clearable
                  @input="fifgoodsProfit(scope.row, scope.$index)"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column  width="100px" align="center">
            <template slot="header" slot-scope="scope">
              <el-tooltip class="item" effect="light" placement="top-start">
                <div><span style="vertical-align: middle">成交单价</span><i class="el-icon-question" style="color:#606266;font-size: 16px;vertical-align: middle;padding-left:5px;"></i></div>
                <div slot="content" style="max-width:400px;">成交单价需要包含运费、杂费与账期利息!</div>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="`goodsList.${scope.$index}.goodsPrice`"
                :rules="rules.goodsPrice"
                label-width="0px"
              >
                <el-input
                  v-model="scope.row.goodsPrice"
                  type="number"
                  clearable
                  @input="fifgoodsProfit(scope.row, scope.$index)"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="选择货权" min-width="300px" v-if="fromType == 'inquiryPrice'">
            <template slot-scope="scope">
              <el-form-item
                v-if="scope.row.ownershipLists.length>0"
                :prop="`goodsList.${scope.$index}.ownershipIds`"
                :rules="validateOwnershipIds(scope.row)"
                label-width="0px"
              >
                <el-checkbox-group v-model="scope.row.ownershipIds" :disabled="scope.row.isDisabled">
                  <div>
                    <el-checkbox :label="item.ownershipId"
                      v-for="item in scope.row.ownershipLists"
                      :key="item.ownershipId">
                      转移价格:{{ item.nowPrice }},可售数量:{{ item.ownershipNum}}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="运费" width="100px" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <el-input
                  size="small"
                  controls-position="right"
                  v-model="scope.row.freightValue"
                  disabled
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="杂费(装卸费)" align="center" width="100px">
            <template slot-scope="scope">
              <el-form-item
                :prop="`goodsList.${scope.$index}.consultation`"
                :rules="rules.consultation"
                label-width="0px"
              >
                <el-input
                  clearable
                  type="number"
                  v-model="scope.row.consultation"
                  @input="fifgoodsProfit(scope.row, scope.$index)"
                  size="small"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="毛利（吨）" width="120px" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="`goodsList.${scope.$index}.goodsProfit`"
                :rules="rules.goodsProfit"
                label-width="0px"
                style="margin-bottom: -20px; padding-bottom: 12px"
              >
                <el-input
                  v-model="scope.row.goodsProfit"
                  disabled
                  size="small"
                ></el-input>

                <span style="color: red; font-size: 12px; margin-bottom: 0px"
                  >最低:{{ scope.row.minProfit }}指导:{{
                    scope.row.normProfit
                  }}</span
                >
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="成交金额" width="100px" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span>{{ scope.row | fifAum }}</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="目标结算吨毛利" width="150px" align="center"  key="30" v-if="sendForm.isDelaySettleOrder == 1">
            <template slot-scope="scope">
              <div>
                <div>
                  <el-form-item label-width="0px"  :prop="`goodsList.${scope.$index}.settlePerTargetProfit`" :rules='rules.settlePerTargetProfit' key="settlePerTargetProfit">
                    <el-input placeholder="请输入" v-model="scope.row.settlePerTargetProfit" disabled style="color:Red">
                      <span slot="prefix">±</span>
                    </el-input>
                  </el-form-item>
                </div>
              </div>

            </template>
          </el-table-column>

          <el-table-column label="采销盈亏占比" width="180px" align="center"  key="31" v-if="sendForm.isDelaySettleOrder == 1">
            <template slot-scope="scope">
              <div>
                <div>
                  <el-form-item label-width="50px"  label="销售" :prop="`goodsList.${scope.$index}.settleSaleProfitRate`" :rules='rules.settleSaleProfitRate' key="settleSaleProfitRate">
                    <el-input placeholder="请输入" type="number" v-model="scope.row.settleSaleProfitRate">
                      <span slot="suffix">%</span>
                    </el-input>
                  </el-form-item>
                  <el-form-item label-width="50px" label="采购">
                    <div style="text-align: left"><span v-if="scope.row.settleSaleProfitRate !==''">{{(100-scope.row.settleSaleProfitRate).toFixed(0)}}</span>%</div>
                  </el-form-item>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="备注" width="120px" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <el-input
                  clearable
                  v-model="scope.row.goodsRemark"
                  size="small"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="底色" width="120px" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <el-select
                  v-model="scope.row.goodsColor"
                  size="small"
                  :disabled="scope.row.isNeedInputColor != 1"
                >
                  <el-option
                    value="蓝底透明"
                    label="蓝底透明"
                    key="1"
                  ></el-option>
                  <el-option
                    value="白底透明"
                    label="白底透明"
                    key="2"
                  ></el-option>
                  <el-option
                    value="黑底透明"
                    label="黑底透明"
                    key="3"
                  ></el-option>
                  <el-option value="黑色" label="黑色" key="4"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="150" label="发货紧急程度" align="center">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`goodsList.${scope.$index}.urgentType`"
                :rules="rules.urgentType"
              >
                <el-select v-model="scope.row.urgentType">
                  <el-option
                    v-for="item in urgentTypeList"
                    :key="item.cddId"
                    :value="item.cddValue"
                    :label="item.cddValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label-width="0px"
                :prop="`goodsList.${scope.$index}.urgentRemark`"
                :rules="rules.urgentRemark"
                v-if="scope.row.urgentType == '必须'"
              >
                <el-input
                  v-model="scope.row.urgentRemark"
                  placeholder="说明原因"
                  style="border: 1px solid #eee"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="100" label="价格类型" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span>{{ scope.row.priceType }}</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="100" label="发货类型" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span>{{ scope.row.deliveryType }}</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="100" label="采购发货时间" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span>{{ scope.row.sendDate }}</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="150" label="采购完成发货时间" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <span>{{ scope.row.endSendDate }}</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="180" label="期望发货日期" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px" v-if="scope.row.isreceiveDate">
                <span>{{ scope.row.receiveDate }}</span>
              </el-form-item>
              <el-form-item  label-width="0px" v-else :prop="`goodsList.${scope.$index}.receiveDate`" :rules="rules.receiveDate">
                     <el-date-picker
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      style="width:140px"
                      v-model="scope.row.receiveDate"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="150" label="从我司购买原因" align="center">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`goodsList.${scope.$index}.fromBuyReason`"
                :rules="rules.fromBuyReason"
              >
                <el-select v-model="scope.row.fromBuyReason">
                  <el-option
                    :value="item.cdd_id"
                    :label="item.cdd_value"
                    :key="item.cdd_id"
                    v-for="item in fromBuyReasonList"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="150" label="客户购买原因" align="center">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`goodsList.${scope.$index}.customerBuyReason`"
                :rules="rules.customerBuyReason"
              >
                <el-select v-model="scope.row.customerBuyReason">
                  <el-option
                    :value="item.cdd_id"
                    :label="item.cdd_value"
                    :key="item.cdd_id"
                    v-for="item in customerBuyReasonList"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <el-button
                  type="text"
                  @click="delGoods(scope.$index)"
                  :disabled="scope.$index == 0"
                  >删除</el-button
                >
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>

        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="12" style="font-size: 12px" :offset="12">
            <el-row>
              <el-col :span="12" style="text-align: right">数量</el-col>
              <el-col :span="12">
                <div style="text-align: right">{{ num }}</div>
              </el-col>
            </el-row>

            <el-row style="margin-top: 10px">
              <el-col :span="12" style="text-align: right">订单总额</el-col>
              <el-col :span="12">
                <div style="text-align: right">￥{{ orderTotalPrice }}</div>
              </el-col>
            </el-row>

            <el-row style="margin-top: 10px">
              <el-col :span="12" style="text-align: right">运费</el-col>
              <el-col :span="12">
                <div style="text-align: right">￥{{ freightTotalPrice }}</div>
              </el-col>
            </el-row>

            <el-row style="margin-top: 10px">
              <el-col :span="12" style="text-align: right">毛利</el-col>
              <el-col :span="12">
                <div style="text-align: right">￥{{ goodsProfitPrice }}</div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="btnLoading" :disabled="isEnableOrder === 0">提交订单</el-button>
      </span>
    </el-dialog>

    <!---新增地址--->
    <el-dialog
      :title="addAddress"
      :visible.sync="dialogVisible2"
      :beforeClose="handleClose2"
      width="500px"
    >
      <div>
        <el-form
          :model="dataInfo"
          size="mini"
          ref="dataInfo"
          :rules="dataRules"
          label-width="120px"
        >
          <el-form-item label="收货人：" prop="contacts">
            <el-input
              v-model="dataInfo.contacts"
              style="width: 220px"
            ></el-input>
          </el-form-item>
          <el-form-item label="收货人手机号：" prop="mobile">
            <el-input v-model="dataInfo.mobile" style="width: 220px"></el-input>
          </el-form-item>
          <el-form-item label="收货地区：" prop="diQuIds">
            <el-cascader
              ref="addressUp"
              filterable
              clearable
              v-model="dataInfo.diQuIds"
              :options="options"
              :props="{
                value: 'areaId',
                label: 'areaName',
                children: 'children',
              }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="真实地址：" prop="address">
            <el-input v-model="dataInfo.address"></el-input>
          </el-form-item>
          <el-form-item label="展示地址：" prop="openAddress">
            <el-input v-model="dataInfo.openAddress "></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-checkbox-group v-model="dataInfo.isDefault">
              <el-checkbox label="设为默认"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div style="color:Red">展示地址: 提供给司机的地址，采购/物流发货时看到的地址建议填写【真实地址】相近的地址</div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">取 消</el-button>
        <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 发货时间  账期提醒 -->
    <el-dialog
      title="提示"
      :visible.sync="tipVisible"
      :show-close="false"
      :close-on-click-modal="false"
      width="480px"
      >
      <div v-if="showOrderType==1" style="padding:12px;font-size:16px;text-align: center;padding:30px">
        此单采购发货时间大于销售期望发货时间,确认已知晓并继续下单!
      </div>
      <div v-if="showOrderType==2" style="padding:12px;font-size:16px;text-align: center;padding:30px">
        请注意！该订单选择的结算方式为【货到付款】,请确认成交单价中包含对应的账期毛利！
      </div>
      <div v-if="showOrderType==3" style="padding:12px;font-size:16px;text-align: center;padding:30px">
        请注意！该订单采购发货时间大于期望发货时间且结算方式为【货到付款】,请明确发货时间与成交单价中已包含对应的账期毛利！
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleOrder">修 改</el-button>
        <el-button type="primary" @click="sureOrder(orderData)" :disabled="clickFlag">确认下单</el-button>
      </span>
    </el-dialog>

    <!-- 新增联系人 -->
    <addContacts ref="addContacts" @update="handleUpdate"></addContacts>

  </div>
</template>
<script>
import {
  createOrder,
  getCustomerList,
  getAreaList,
  getFromCompanyList,
  getPreOrderContent,
  customerAddress,
  addressUpdate,
  addressDelete,
  getCustomerSetting,
  paymentTypeListAPI,
  getSaleUserListAPI,
  getMyGoodsOwnerShipAPI
} from "@/api/allInLine/inquiry";
import { customerNewContactList } from '@/api/company';
import { validatePhone } from "@/utils/validate";
import { formatDate } from "@/utils/date";
import { urgentTypeList } from "@/utils/constant";
import { mapGetters } from "vuex";
import { Message } from "element-ui";
import addContacts from '@/views/cms/components/addContacts.vue';
import {getConfigList} from '@/api/partner';
import {getCustomerDefaultNum} from "@/api/order";
import crmTag from "@/views/components/crmTag";
import {copyText} from '@/utils/index.js'
import {validateInt} from '@/utils/validate'

const defaultSendForm = {
  formId:'',//订单ID
  // payDate: "",
  customerId: "",
  inquiryUserId:"",
  customerName: "",
  fromCompany: "",
  sendTypes: "",
  shippingType: "",
  // expectPayDate: "",
  // expectPayHour: "",
  payTypes: "",//支付方式
  //createAbstract: "", //支付摘要
  isArrears: "",//客户是否欠款
  arrearsRemark: "",//欠款说明
  reputation:"",//客户信誉
  isTimeSure: 2,
  addressId: "",
  goodsList: [],
  exchangeRate: 1,
  paymentItemCode: '',//支付摘要判断码
  paymentDeposit: '',//支付定金
  paymentDate: '',//贷款日期
  paymentDayNum: '',//客户账期 贷款期限
  paymentInterest:'',//账期利息
  paymentAmount:'',//锡商银行贷款金额
  orderCustomerType:'',
  isBatchPaid:'',//
  carNum:'',//车
  perDeposit:'',//每车的价格
  balance:'',//发货的余款
  isIntentionOrder:0, //意向订单
  isDelaySettleOrder:0,//是否后结算
};
const defaultGoodsList = {
  categoryName: "", //品名1
  goodsSn: "", // 牌号2
  isNeedInputColor: "", // 是否需要底色3
  inquiryId: "", //询价ID(未询价下单传0)
  inquiryPriceId:"",//报价id
  goodsDetailId: "", //规格商品ID(未询价下单需填)4
  warehouseName: "", //仓库名称
  payTypes: "", //支付方式
  goodsNum: 0, //成交数量
  goodsPrice: "", //成交单价5
  freightValue: 0, //运费
  consultation: 0, //杂费(装卸费)
  goodsColor: "", //底色
  goodsRemark: "", //备注
  receiveDate: "", //期望到货时间
  urgentType: "", //发货紧急程度
  urgentRemark: "", //发货紧急度备注
  deliveryType: "", //发货类型(公司发货、采购发货)
  sendDate: "", //采购发货时间
  endSendDate: "",//采购完成发货时间
  priceId: "",
  priceType: "",
  purchasePrice: 0, //6
  sendTypes: "", //7
  goodsProfit: "", //商品吨毛利
  applyId: "",
  fromBuyReason: "",
  customerBuyReason: "",
  minProfit: 0,
  normProfit: 0,
  ownershipLists: [],
  ownershipIds:[],
  settlePerTargetProfit:100,
  settleSaleProfitRate:50,
};
const defaultDataInfo = {
  companyId: "",
  contacts: "",
  mobile: "",
  provinceId: "",
  cityId: "",
  areaId: "",
  areaInfo: [],
  address: "",
  isDefault: 0,
  type: 1,
  id: "",
  diQuIds:[],
  openAddress:''
};
export default {
  name: "index",
  data() {
    const isvalidatePhone = (rule, value, callback) => {
      if (!validatePhone(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    const validateGoodsNum = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('不能小于0'))
      }
      callback()
    };
    const validatePrice = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('不能小于0元'))
      }
      callback()
    };
    const validatebalance = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error('需大于0'))
      }
      callback()
    };
    const validatepaymentDeposit =  (rule, value, callback) => {
      if (value <= 0 && this.sendForm.paymentItemCode=='BANK_PAY_Item4') {
        callback(new Error('需大于0'))
      }else if(value < 0){
        callback(new Error('不能小于0元'))
      }
      callback()
    };

    const validatetargetSettlementGrossProfit = (rule, value, callback)=> {
      if (!validateInt(value)) {
        callback(new Error('需大于等于0整数'))
      }
      callback()
    }
    const validatesaleGrossProfitPercentage = (rule, value, callback)=> {
      if (!validateInt(value) || value < 0 || value > 100) {
        callback(new Error('需在0到100之间的整数'))
      }
      callback()
    }

    return {
      clickFlag:false,
      fromType:'',
      inquiryUserList:[],
      orderData:{},
      tipVisible: false,
      showOrderType:'',
      addAddress: "新增地址",
      priceIds: "",
      inquiryIds: "",
      applyId: "",
      urgentTypeList: urgentTypeList,
      fromCompanyList: [], //供货方公司
      companyQuerySearchList: [],
      customerBuyReasonList: [],
      fromBuyReasonList: [],
      receiveAreaId: "",
      chooseAddressId: "",
      type: "",
      dialogVisible: false,
      dialogVisible2: false,
      btnLoading: false,
      btnLoading2: false,
      dialogLoading: false,
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      pickerOptions2: {
        disabledDate(time) {
          const currentDate = Date.now() - 8.64e7; // 当前日期
          const thirtyDaysLater = new Date();
          thirtyDaysLater.setDate(thirtyDaysLater.getDate() + 30); // 当前日期后30天
          return time.getTime() < currentDate || time.getTime() > thirtyDaysLater.getTime();
        }
      },
      sendForm: JSON.parse(JSON.stringify(defaultSendForm)),
      rules: {
        customerId: [
          { required: true, message: "请选择客户名称", trigger: "change" },
        ],
        inquiryUserId: [
          {required: true, message: "请选择业务员", trigger: "change"}
        ],
        sendTypes: [
          { required: true, message: "请选择物流方式", trigger: "change" },
        ],
        buyerAddressId: [
          { required: true, message: "请输入地址", trigger: "change" },
        ],
        addressId: [
          { required: true, message: "请选择地址", trigger: "change" },
        ],
        shippingType: [
          { required: true, message: "请选择运费方式", trigger: "change" },
        ],
        payTypes: [
          { required: true, message: "请选择支付方式", trigger: "change" },
        ],
        paymentItemCode: [
          { required: true, message: "请选择支付摘要", trigger: "change" },
        ],
        paymentDeposit: [
          { required: true, message: "请输入支付定金", trigger: "blur" },
          {validator:validatepaymentDeposit,trigger: "blur"}
        ],
        paymentDate: [
          { required: true, message: "请选择货款最晚付清日期", trigger: "change" },
        ],
        carNum: [
          { required: true, message: "此项必填", trigger: "change" },
        ],
        balance: [
          { required: true, message: "此项必填", trigger: "blur" },
          {validator:validatebalance,trigger: "blur"}
        ],
        paymentDayNum: [
          { required: true, message: "请输入该选项", trigger: "blur" },
          {validator:validateGoodsNum,trigger: "blur"}
        ],
        paymentInterest: [
          { required: true, message: "请输入账期利息", trigger: "blur" },
          {validator:validatePrice,trigger: "blur"}
        ],
        paymentAmount: [
          { required: true, message: "请输入向锡商银行贷款金额", trigger: "blur" },
          {validator:validatePrice,trigger: "blur"}
        ],
        isArrears: [
          { required: true, message: "请选择客户是否有未清款项", trigger: "change" },
        ],
        arrearsRemark: [
          { required: true, message: "请输入未清款项说明", trigger: "blur" },
        ],
        reputation: [
          { required: true, message: "请输入客户信誉", trigger: "blur" },
        ],
        goodsNum: [
          { required: true, message: "请输入成交数量", trigger: "blur" },
          {validator:validateGoodsNum,trigger: "blur"}
        ],
        freightValue: [
          { required: true, message: "请输入运费金额", trigger: "blur" },
        ],
        consultation: [
          { required: true, message: "请输入杂费(装卸费)", trigger: "blur" },
          {validator:validatePrice,trigger: "blur"}
        ],
        goodsPrice: [
          { required: true, message: "请输入成交单价", trigger: "blur" },
          {validator:validatePrice,trigger: "blur"}
        ],
        goodsProfit: [
          { required: true, message: "请输入毛利", trigger: "blur" },
        ],
        urgentRemark: [
          { required: true, message: "请输入紧急程度备注", trigger: "blur" },
        ],
        urgentType: [
          { required: true, message: "请选择紧急程度", trigger: "change" },
        ],
        // payDate: [
        //   { required: true, message: "请选择付款截止时间", trigger: "change" },
        // ],
        exchangeRate: [{required: true,message: "请输入美元汇率",trigger: "blur"}],
        customerBuyReason: [{ required: true,message: "请选择",trigger: "change"}],
        fromBuyReason: [{ required: true, message: "请选择",trigger: "change"}],
        receiveDate: [{ required: true,message: "请选择",trigger: "change" }],
        orderCustomerType:[{ required: true,message: "请选择",trigger: "change"}],
        isBatchPaid:[{ required: true,message: "请选择",trigger: "change"}],
        isIntentionOrder:[{ required: true,message: "请选择",trigger: "change"}],
        settlePerTargetProfit:[
          {validator:validatetargetSettlementGrossProfit,trigger: "blur"},
        ],
        settleSaleProfitRate:[
          { required: true,message: "此项必填",trigger: "blur"},
          {validator:validatesaleGrossProfitPercentage,trigger: "blur"},
        ]
      },
      options: [],
      contractRemarks: [], //类型描述下拉
      companyLoading: false,
      goodsList: JSON.parse(JSON.stringify(defaultGoodsList)),
      props: {
        value: "areaName",
        label: "areaName",
        children: "areaChildList",
      },
      dataRules: {
        contacts: [
          { required: true, message: "请输入收货人", trigger: "blur" },
        ],
        mobile: [
          { required: true, trigger: "blur", validator: isvalidatePhone },
        ],
        diQuIds: [
          { required: true, message: "请选择所在地区", trigger: "change" },
        ],
        address: [
          { required: true, message: "请输入真实地址", trigger: "blur" },
        ],
        openAddress: [
          { required: true, message: "请输入展示地址", trigger: "blur" },
        ],
      },
      canUseAddressList: [],
      noUseAddressList: [],
      paymentTypeLists: [], //结算方式列表
      dataInfo: JSON.parse(JSON.stringify(defaultDataInfo)),
      usesAddress: false,
      isChina: "",
      chargeName: "",
      subChargeNames: "",
      contactLoading:false,
      deliverMobile: '',
      deliverMobileList:[],
      invoiceMobile: '',
      invoiceMobileList: [],
      choosePaytypeObj:{},
      orderCustomerTypeList:[],
      orderCustomerType:'',
      defaultNum:0,
      isEnableOrder:'',
      outTimeUnPaidAmount:0,
      customerTag:'',
      inpuiryIsBatchPaid:'',
      visible:false,
      chengDuiBankList:[],
      chengDuiTipFile:'',
      pricePayTypes:'',
    };
  },
  watch: {
    'sendForm.isDelaySettleOrder'(newVal){
      this.$nextTick(() => {
        setTimeout(()=>{
          this.$refs.sendForm.clearValidate(); //
          this.$refs.sendForm.validate(); // 重新触发验证
        },500)
      });
    },
  },
  computed: {
    ...mapGetters(["name", "mobile", "userId"]),
    num() {
      let orderNum = 0;
      this.sendForm.goodsList.forEach((item) => {
        orderNum += parseFloat(item.goodsNum);
      });
      return orderNum.toFixed(2);
    },
    // 计算订单总额
    orderTotalPrice() {
      let orderPrice = 0;
      this.sendForm.goodsList.forEach((item) => {
        let goodsNum = item.goodsNum ? parseFloat(item.goodsNum) : 0;
        let goodsPrice = item.goodsPrice ? parseFloat(item.goodsPrice) : 0;
        let sun;
        sun = goodsPrice * goodsNum;
        sun = sun.toFixed(4);
        sun = parseFloat(sun) * 1;
        orderPrice += sun;
      });
      return orderPrice.toFixed(4);
    },
    freightTotalPrice() {
      let freightPrice = 0;
      this.sendForm.goodsList.forEach((item) => {
        freightPrice += parseFloat(
          item.freightValue != "" ? item.freightValue : 0
        );
      });
      return freightPrice.toFixed(2) ? freightPrice.toFixed(2) : "";
    },
    // 计算总毛利
    goodsProfitPrice() {
      let ProfitPrice = 0;
      this.sendForm.goodsList.forEach((item) => {
        let goodsNum = item.goodsNum ? parseFloat(item.goodsNum) : 0;
        let goodsProfit = item.goodsProfit ? parseFloat(item.goodsProfit) : 0;
        let sun;
        sun = goodsProfit * goodsNum;
        sun = sun.toFixed(2);
        sun = parseFloat(sun) * 1;
        ProfitPrice+=sun
      });
      return ProfitPrice.toFixed(2) ? ProfitPrice.toFixed(2) : 0;
    },

    isPayTypes(){
     let i = this.sendForm.goodsList.findIndex((item) => {
       return item.payTypes == '承兑'
      });
     return i != -1
    },
  },
  components: {
    // addCustomer,
    addContacts,
    crmTag
  },
  created() {
  },
  filters: {
    fifAum(item) {
      let goodsNum = item.goodsNum ? parseFloat(item.goodsNum) : 0;
      if (goodsNum) {
        let goodsPrice = item.goodsPrice ? parseFloat(item.goodsPrice) : 0;
        let sun = goodsPrice * goodsNum;
        sun = sun.toFixed(4);
        sun = parseFloat(sun) * 1;
        return sun;
      } else {
        return "";
      }
    },
  },
  methods: {

    downFile(){
      window.open(this.chengDuiTipFile)
    },
    async copyItem(item){
      let text = '账户名称：'+item.fromCompany+'\n'+
        '承兑账号：'+item.bankAccount+'\n'+
        '开户银行：'+item.bankName+'\n'+
        '行号：'+item.bankCode+'\n'
      try {
        await copyText(text);
        this.$message.success("复制成功");
      } catch (err) {
        this.$message.error("复制失败");
      }
    },
    countperDeposit(){
      if(this.sendForm.paymentDeposit && this.sendForm.carNum ){
        this.sendForm.perDeposit = Number((this.sendForm.paymentDeposit/this.sendForm.carNum).toFixed(2))
      }
    },
    //获取订单分类列表
    getOrderCustomerType(){
      getConfigList({status:1}).then((res)=>{
         let orderCustomerType = res.find((el)=>{
           return  el.cdtCode == 'order_customer_type'
         })
         this.orderCustomerTypeList = orderCustomerType ? orderCustomerType.data : []
      })
    },
    // 获取发票联系人
    handleInvoiceMobile() {
      this.contactLoading = true;
       customerNewContactList({
        pageNum: 1,
        pageSize: 100,
        customerId: this.sendForm.customerId?this.sendForm.customerId:'',
        isMy: 1,
        contactDuty:'发票联系人'
       }).then((res) => {
        this.contactLoading = false;
        this.invoiceMobileList = res.list;
       }).catch(() => {
        this.contactLoading = false;
      })
    },
    // 获取发货联系人
    handleDeliverMobile() {
      this.contactLoading = true;
      customerNewContactList({
        pageNum: 1,
        pageSize: 100,
        customerId: this.sendForm.customerId?this.sendForm.customerId:'',
        isMy: 1,
        contactDuty:'发货联系人'
      }).then((res) => {
        this.contactLoading = false;
        this.deliverMobileList = res.list;
      }).catch(() => {
        this.contactLoading = false;
      })
    },
    // 显示新增发货 发票联系人
    showContact(type, item, contactDutyProp) {
      if (type == 'add') {
        this.$refs.addContacts.showPop(type, item, contactDutyProp);
      }
    },
    // 新增发货 发票联系人
    handleUpdate(item) {
      if (item.contactDuty == '发货联系人') {
        this.deliverMobile=item.contactMobile
      }else if (item.contactDuty == '发票联系人') {
        this.invoiceMobile=item.contactMobile
      }
    },

    // 货权数量校验
    validateOwnershipIds(row) {
      return [{
        validator: (rule, value, callback) => {
          if (!row.isDisabled) {
            let sum = 0
            value.forEach((el) => {
              let i = row['ownershipLists'].findIndex((ee) => {
                return el == ee.ownershipId
              })
              if (i!= -1) {
                sum = sum + row['ownershipLists'][i]['ownershipNum']
              }
            })
            if(value.length == 0){
              callback(new Error('请选择货权'))
            }else if (sum < row['goodsNum']) {
              callback(new Error('货权可售数量不足'))
            } else {
              callback()
            }
          }else {
            callback()
          }
        }
      }]
    },
    changePaymentCode() {
      if (this.sendForm.payTypes == 'BANK_PAY') {
        this.sendForm.paymentDeposit = '';
        this.sendForm.paymentDate = '';
        this.sendForm.carNum = '';
        this.sendForm.perDeposit = '';
        this.sendForm.balance = '';
      } else if (this.sendForm.payTypes=='COD_PAY'||this.sendForm.payTypes=='COD_PAY2') {
        this.sendForm.paymentDayNum = '';
        this.sendForm.paymentInterest = '';
      }
      if(this.sendForm.paymentItemCode=='BANK_PAY_Item4' || this.inpuiryIsBatchPaid == 1){
          this.sendForm.isBatchPaid = 1
      }else{
        this.sendForm.isBatchPaid = ''
      }
    },
    changeArrears() {
      this.sendForm.arrearsRemark = '';
      this.sendForm.reputation = '';
    },
    //变更支付方式
    changePayTypes(payTypes) {
      this.sendForm.isArrears = '';//是否有未清款项
      this.sendForm.arrearsRemark = '';//未清款项说明
      this.sendForm.reputation = '';//客户信誉
      this.sendForm.paymentItemCode = '';
      this.sendForm.paymentDeposit = '';
      this.sendForm.paymentDate = '';
      this.sendForm.paymentDayNum = '';
      this.sendForm.paymentAmount = '';
      this.sendForm.paymentInterest = '';
      this.sendForm.carNum = '';
      this.sendForm.perDeposit = '';
      this.sendForm.balance = '';
      this.choosePaytypeObj = this.paymentTypeLists.find(res => res.code == payTypes);
      if (payTypes=='XISHANG_PAY') {
        this.sendForm.paymentItemCode = 'XISHANG_PAY_Item1';
      }
    },
    // 杂费(装卸费)
    fifgoodsProfit(item, index) {
      let goodsNum = item.goodsNum ? parseFloat(item.goodsNum) : 0;
      let c = JSON.parse(JSON.stringify(this.sendForm.goodsList[index]));
      if (goodsNum) {
        let purchasePrice = item.purchasePrice
          ? parseFloat(item.purchasePrice)
          : 0;
        let freightValue = item.freightValue
          ? parseFloat(item.freightValue)
          : 0;
        let consultation = item.consultation
          ? parseFloat(item.consultation)
          : 0;
        let goodsPrice = item.goodsPrice ? parseFloat(item.goodsPrice) : 0;
        let goodsProfit = (
          goodsPrice -
          purchasePrice -
          consultation -
          freightValue / goodsNum
        ).toFixed(2);
        goodsProfit = parseFloat(goodsProfit) * 1;
        c.goodsProfit = goodsProfit;
      } else {
        c.goodsProfit = "";
      }
      this.sendForm.goodsList.splice(index, 1, c);
    },

    changeUsesAddress() {
      if (this.usesAddress) {
        this.dataInfo.actualBuyerAddress =
          this.dataInfo.area[0] +
          " " +
          this.dataInfo.area[1] +
          " " +
          this.dataInfo.area[2] +
          " " +
          this.dataInfo.detailAddress;
        this.dataInfo.actualBuyerName = this.dataInfo.buyerNickName;
        this.dataInfo.actualBuyerMobile = this.dataInfo.buyerMobile;
      }
    },

    //切换物流方式
    changeShippingType() {
      if (this.sendForm.sendTypes == "送到") {
        //物流方式为送到，需计算运费
        this.sendForm.shippingType = "free_shipping";
      }
      if (this.sendForm.sendTypes == "自提") {
        //当物流方式为自提时，运费方式固定为“需方承担运费”
        this.sendForm.shippingType = "logistics_shipping";
        this.sendForm.addressId = "";
      }
    },

    //获取客户配置
    getCustomerSettingList() {
      getCustomerSetting().then((res) => {
        res.forEach((el) => {
          if (el.cdt_code == "customer_industry") {
            this.customerIndustryList = el.data;
          } else if (el.cdt_code == "customer_buy_reason") {
            this.customerBuyReasonList = el.data;
          } else if (el.cdt_code == "from_buy_reason") {
            this.fromBuyReasonList = el.data;
          }
        });
      });
    },

    //搜索客户
    remoteMethod(key) {
      this.companyLoading = true;
      getSuggestCompanyList({ keyword: key })
        .then((res) => {
          this.buyerCompanyList = res;
          this.companyLoading = false;
        })
        .catch(() => {
          this.companyLoading = false;
        });
    },

    //获取省市区列表
    getAddressListData() {
      getAreaList().then((res) => {
        this.options = res;
      });
    },
    //显示立即下单
    showPop(type, data,pricePayTypes) {
      this.dialogVisible = true;
      this.pricePayTypes = pricePayTypes;
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
      this.getCustomerSettingList();
      this.getAddressListData();
      this.getPaymentTypeList();
      this.getOrderCustomerType()
      this.type = type;
      if (type == "onePrice") {//一口价
        this.fromType = 'onePrice';
        const onePriceNum = data.map((item) => item.priceId);
        onePriceNum.forEach((item, index) => {
          this.sendForm.goodsList.push(
            JSON.parse(JSON.stringify(this.goodsList))
          );
          this.sendForm.goodsList[index].priceId = item;
        });
        this.priceIds = onePriceNum.join(",");
      } else if (type == "inquiryPriceIds") {//询价
        this.fromType = 'inquiryPrice';
        this.sendForm.inquiryUserId = data[0].inquiryUserId ? data[0].inquiryUserId : '';
        const priceIdsNum = data.map((item) => item.priceId);
        priceIdsNum.forEach((item, index) => {
          this.sendForm.goodsList.push(
            JSON.parse(JSON.stringify(this.goodsList))
          );
          this.sendForm.goodsList[index].priceId = item;
        });
        this.inquiryPriceIds = priceIdsNum.join(",");
      }
      this.fromCompanyLists();
      this.getPreOrderInfo().then(() => {
        if (type == "inquiryPriceIds") {
          this.getOwnership(this.inquiryPriceIds)
        }
        if(this.sendForm.customerId){
          this.getSaleUserList()
        }
      });
    },
    // 获取货权列表
    getOwnership(inquiryPriceIds) {
      getMyGoodsOwnerShipAPI({ inquiryPriceIds }).then((res) => {
        this.sendForm.goodsList.forEach((el, index) => {
          let c = JSON.parse(JSON.stringify(el))
          let i = res.findIndex((ee) => {
            return ee.inquiryPriceId == el.inquiryPriceId
          })
          if (i != -1) {
            c.ownershipLists= res[i]['ownershipList']
            let sum = 0
            c.ownershipLists.forEach(element => {
              sum += element.ownershipNum;
            });
            c.isDisabled = c.goodsNum > sum
            if (res[i]['ownershipList'].length == 1 && res[i]['ownershipList'][0]['ownershipNum'] >= el.goodsNum) {
              c.ownershipIds = []
              c.ownershipIds.push(res[i]['ownershipList'][0]['ownershipId'])
            }
          }
          this.sendForm.goodsList.splice(index,1,c)
        })
       })
    },
    // 获取下单商品内容
    getPreOrderInfo() {
      this.dialogLoading = true;
     return getPreOrderContent({
        inquiryPriceIds: this.inquiryPriceIds,
        priceIds: this.priceIds,
        applyIds: this.applyId,
        pricePayTypes:this.pricePayTypes
      }).then((res) => {
        this.dialogLoading = false;
        this.orderCustomerType = res.orderCustomerType
        this.chengDuiBankList = res.chengDuiBankList
        this.chengDuiTipFile = res.chengDuiTipFile
        this.sendForm.formId = res.formId;//获取订单ID，避免重复提交
        this.sendForm.customerId = res.customerId != 0 ? res.customerId : "";
        this.sendForm.customerName = res.customerName;
        this.sendForm.sendTypes = res.sendTypes;
        this.sendForm.fromCompany = res.fromCompany;
        this.sendForm.orderCustomerType = res.orderCustomerType
        this.receiveAreaId = res.receiveAreaId;
        this.chooseAddressId = res.receiveAreaId;
        this.sendForm.exchangeRate = 1;
        this.inpuiryIsBatchPaid = res.isBatchPaid;
        this.sendForm.isBatchPaid = res.isBatchPaid
        if (this.sendForm.sendTypes == "送到") {
          this.sendForm.shippingType=this.sendForm.shippingType == "" ? "free_shipping": this.sendForm.shippingType;
        }
        res.goodsList.forEach((item, index) => {
          for (let key in defaultGoodsList) {
            this.sendForm.goodsList[index][key] = item[key] ? item[key] : defaultGoodsList[key];
            this.sendForm.goodsList[index].fromBuyReason = 240;
            this.sendForm.goodsList[index].customerBuyReason = 234;
          }
          if (item.sendTypes == "自提") {
            this.sendForm.goodsList[index].goodsRemark=item.payTypes == "承兑" ? "承兑自提" : "含税自提";
          } else if (item.sendTypes == "送到") {
            this.sendForm.goodsList[index].goodsRemark=item.payTypes == "承兑" ? "承兑送到" : "含税送到";
          }
          this.sendForm.goodsList[index].goodsPrice = "";
          // 发货紧急程度
          this.sendForm.goodsList[index].urgentType = item.inquiryUrgentType;
          this.sendForm.goodsList[index].urgentRemark = item.inquiryUrgentRemark;
          // 是否有期望发货时间
          this.sendForm.goodsList[index].isreceiveDate = item.receiveDate != '' ? true : false;
        });
        if (res.customerId != 0) {
          this.getCustomerAddress(res.customerId);
          this.companyQuerySearch(res.customerName, "all");
          this.getCustomerWy()
        }
      }).catch((err) => {
        this.dialogLoading = false;
      });
    },

    //根据客户获取收货地址
    getCustomerAddress(val) {
      customerAddress({ customerId: val, areaId: this.chooseAddressId }).then(
        (res) => {
          this.canUseAddressList = res.canUse;
          this.noUseAddressList = res.noUse;
        }
      );
    },

    getPaymentTypeList() {
      paymentTypeListAPI().then((res) => {
        this.paymentTypeLists = res;
      });
    },

    //关闭立即下单
    handleClose() {
      this.dialogVisible = false;
      this.$refs.sendForm.clearValidate();
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
    },
    //关闭新增地址
    handleClose2() {
      this.dataInfo = JSON.parse(JSON.stringify(defaultDataInfo));
      this.$refs.dataInfo.resetFields();
      this.dialogVisible2 = false;
    },

    // 新增 修改收货地址
    showAddAddress(type, item) {
      this.dialogVisible2 = true;
      if (type == "edit") {
        this.addAddress = "修改地址";
        this.dataInfo.companyId = item.companyId;
        this.dataInfo.provinceId = item.provinceId;
        this.dataInfo.contacts = item.contacts;
        this.dataInfo.cityId = item.cityId;
        this.dataInfo.area_id = item.areaId;
        this.dataInfo.areaInfo = item.areaInfo;
        this.dataInfo.mobile = item.mobile;
        this.dataInfo.address = item.address;
        this.dataInfo.diQuIds = [item.provinceId, item.cityId, item.areaId];
        this.dataInfo.isDefault = item.isDefault == 1;
        this.dataInfo.type = 1;
        this.dataInfo.id = item.id;
        this.dataInfo.openAddress = item.openAddress
      } else {
        this.addAddress = "新增地址";
        this.dataInfo.companyId = item.customerId;
        this.options.forEach((item) => {
          if (item.areaId == this.receiveAreaId) {
            this.dataInfo.diQuIds = [this.receiveAreaId, 0, 0];
            return;
          } else {
            item.children.forEach((item2) => {
              if (item2.areaId == this.receiveAreaId) {
                this.dataInfo.diQuIds = [item2.areaParentId, item2.areaId, 0];
                return;
              } else {
                item2.children.forEach((item3) => {
                  if (item3.areaId == this.receiveAreaId) {
                    this.dataInfo.diQuIds = [
                      item2.areaParentId,
                      item3.areaParentId,
                      item3.areaId,
                    ];
                    return;
                  }
                });
              }
            });
          }
        });
        this.dataInfo.area_id = this.receiveAreaId;
      }
    },
    // 删除收货地址
    showDelAddress(item) {
      addressDelete({ id: item.id })
        .then((res) => {
          Message.success("删除成功");
          this.getCustomerAddress(this.sendForm.customerId);
        })
        .catch((err) => {});
    },

    //确认新增地址
    handleConfirm2() {
      const data = JSON.parse(JSON.stringify(this.dataInfo));
      this.$refs.dataInfo.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          data.provinceId = this.dataInfo.diQuIds[0] ? this.dataInfo.diQuIds[0] : "";
          data.cityId = this.dataInfo.diQuIds[1] ? this.dataInfo.diQuIds[1] : "";
          data.areaId = this.dataInfo.diQuIds[2] ? this.dataInfo.diQuIds[2] : "";
          data.areaInfo = this.$refs["addressUp"].getCheckedNodes()[0].pathLabels.join("");
          data.isDefault = data.isDefault ? 1 : 0;
          data.type = 1;
          delete data.diQuIds;
          addressUpdate(data).then((res) => {
              this.getCustomerAddress(this.sendForm.customerId);
              Message.success("操作成功");
              this.btnLoading2 = false;
              this.dialogVisible2 = false;
              this.dataInfo = JSON.parse(JSON.stringify(defaultDataInfo));
            }).catch((err) => {
              this.btnLoading2 = false;
            });
        }
      });
    },
    // 删除订单
    delGoods(index) {
      this.sendForm.goodsList.splice(index, 1);
    },
    // 修改订单
    cancleOrder() {
      this.btnLoading = false;
      this.tipVisible = false
    },

    sureOrder(data) {
      this.clickFlag = true;
      let dataNew = JSON.parse(JSON.stringify(data));
      dataNew.pricePayTypes = this.pricePayTypes
      createOrder(dataNew).then((res) => {
        this.$emit("update");
        Message.success("生成订单成功");
        this.clickFlag = false;
        this.btnLoading = false;
        this.tipVisible = false;
        this.handleClose();
      }).catch((err) => {
        this.btnLoading = false;
        this.clickFlag = false;
        //重新获取订单信息
        getPreOrderContent({
          inquiryPriceIds: this.inquiryPriceIds,
          priceIds: this.priceIds,
          applyIds: this.applyId,
        }).then((res) => {
          this.sendForm.formId = res.formId;//获取订单ID，避免重复提交
          }).catch((err) => {
          });
      });
    },

    // 确认生成订单
    handleConfirm(){
      this.$refs.sendForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          const data = JSON.parse(JSON.stringify(this.sendForm));
          delete data.carNum
          delete data.balance
          if (data.sendTypes == "自提") {
            data.addressId = "";
            data.shippingType = "buyer_shipping";
          }
          // data.expectPayDate = formatDate(new Date(data.payDate), "yyyy-MM-dd");
          // data.expectPayHour = formatDate(new Date(data.payDate), "hh:mm:ss");
          delete data.payDate;
          data.goodsList.forEach((item,i) => {
            delete item.categoryName;
            delete item.goodsSn;
            delete item.isNeedInputColor;
            delete item.goodsDetailId;
            delete item.purchasePrice;
            delete item.sendTypes;
            delete item.ownershipLists;
            item.ownershipIds = item.ownershipIds.join(',')
            if(item.settleSaleProfitRate !== ''){
              item.settlePurchaseProfitRate = (100 - item.settleSaleProfitRate).toFixed(0)
            }
          })
          let flag = 0;
          for (let i = 0; i < data.goodsList.length; i++){
            let item = data.goodsList[i];
            //  发货时间与支付方式判断
            if (item.sendDate > item.receiveDate && data.payTypes != 'COD_PAY') {
              flag = 1;
              break;
            } else if (item.sendDate > item.receiveDate && data.payTypes == 'COD_PAY') {
              flag = 3;
              break;
            } else if (item.sendDate <= item.receiveDate && data.payTypes == 'COD_PAY') {
              flag = 2;
              break;
            }
          }
          if (flag == 1) {
            this.tipVisible = true;
            this.showOrderType = 1;
          } else if (flag == 3) {
            this.tipVisible = true;
            this.showOrderType = 3;
          } else if (flag == 2) {
            this.tipVisible = true;
            this.showOrderType = 2;
          } else {
            this.sureOrder(data)
          }
          this.orderData = JSON.parse(JSON.stringify(data))
        } else {
          Message.error("请检查必填项哦!");
        }
      });
    },
    //客户名称输入匹配
    companyQuerySearch(queryString, tab) {
      if (queryString && queryString != "") {
        if (tab == "all") {
          getCustomerList({ keywords: queryString, tab: "all" }).then((res) => {
            this.companyQuerySearchList = res;
            let index = this.companyQuerySearchList.findIndex((el) => {
              return el.customerId == this.sendForm.customerId;
            });
            if (index != -1) {
              this.getGoodsName(this.companyQuerySearchList[index]);
            }
          });
        } else {
          getCustomerList({ keywords: queryString }).then((res) => {
            this.companyQuerySearchList = res;
          });
        }
      }
    },
    handleChange(val) {
      this.sendForm.addressId = "";
      this.sendForm.inquiryUserId = ''
      if (val) {
        this.getCustomerAddress(val);
        let index = this.companyQuerySearchList.findIndex((el) => {
          return el.customerId == val;
        });
        if (index != -1) {
          this.getGoodsName(this.companyQuerySearchList[index]);
        }
        this.getSaleUserList()
        this.getCustomerWy()
      }
    },
    getCustomerWy(){
      this.defaultNum = 0
      this.customerTag = ''
      if(this.sendForm.customerId){
        getCustomerDefaultNum({customerId:this.sendForm.customerId}).then((res)=>{
          this.defaultNum = res.defaultNum
          this.isEnableOrder = res.isEnableOrder
          this.outTimeUnPaidAmount = res.outTimeUnPaidAmount
          this.customerTag = res.customerTag
        })
      }
    },
    // 获取业务员列表
    getSaleUserList() {
      this.inquiryUserList = []
      getSaleUserListAPI({
        type:"inquiry",
        customerId:this.sendForm.customerId
      }).then((res) => {
        this.inquiryUserList = res;
        if (this.inquiryUserList.length == 1) {
          this.sendForm.inquiryUserId=this.inquiryUserList[0].userId
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    // 获取负责人 协助人 发货联系人 发票联系人
    getGoodsName(val) {
      this.chargeName = val.chargeName;
      this.subChargeNames = val.subChargeNames;
      this.deliverMobile = val.deliverMobile;
      this.invoiceMobile = val.invoiceMobile;
      this.sendForm.customerName = val.customerName;
    },

    // 供货方列表
    fromCompanyLists() {
      getFromCompanyList().then((res) => {
        this.fromCompanyList = res;
      });
    },

  }
};
</script>

<style lang="scss">
.addOrderStyle{
  .el-form-item__content span {
    font-size: 12px;
  }
  #my-table th:nth-child(6) .cell {
    color: red;
  }
}
.areaInfoRadio .el-radio.is-bordered{
   height: auto;
}
</style>
